
package com.j2eefast.bussiness.contract.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.j2eefast.bussiness.contract.entity.*;
import com.j2eefast.bussiness.contract.service.*;
import com.j2eefast.bussiness.contract.utils.MonthSheetWriteHandler;
import com.j2eefast.common.core.business.annotaion.BussinessLog;
import com.j2eefast.common.core.controller.BaseController;
import com.j2eefast.common.core.enums.BusinessType;
import com.j2eefast.common.core.utils.PageUtil;
import com.j2eefast.common.core.utils.ResponseData;
import com.j2eefast.common.core.utils.ToolUtil;
import com.j2eefast.common.core.utils.ValidatorUtil;
import com.j2eefast.framework.annotation.RepeatSubmit;
import com.j2eefast.framework.sys.service.SysUserService;
import com.j2eefast.framework.utils.Constant;
import com.j2eefast.framework.utils.Global;
import com.j2eefast.framework.utils.UserUtils;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * <p>设备规范列表</p>
 *
 * @author: summer
 * @date: 2021-05-31 14:41
 * @web: http://www.letukeji.cn
 * @version: 1.0.1
 */
@Controller
@RequestMapping("/bus/standardList")
public class BusStandardListController extends BaseController {

	private String urlPrefix = "modules/bus/standardList";
	@Autowired
	private BusStandardListService busStandardListService;
	@Autowired
	private BusStandardService busStandardService;




	@RequiresPermissions("bus:standardList:view")
	@GetMapping()
	public String process() {
		return urlPrefix + "/index";
	}

	@RequestMapping("/list")
	@RequiresPermissions("bus:standardList:list")
	@ResponseBody
	public ResponseData list(@RequestParam Map<String, Object> params) {
		String equipmentType = (String) params.get("equipmentType");
		PageUtil page = busStandardListService.findPage(params);
		return success(page);
	}

	/**
	 * 删除
	 */
	@BussinessLog(title = "删除", businessType = BusinessType.DELETE)
	@RequestMapping( value = "/del", method = RequestMethod.POST)
	@RequiresPermissions("bus:standardList:del")
	@RequiresRoles(Constant.SU_ADMIN)
	@ResponseBody
	public ResponseData delete(Long[] ids) {
		return busStandardListService.deleteByIds(ids)?success(): error("删除失败!");
	}


	/**
	 * 修改出入库 页面
	 */
	@RequiresPermissions("bus:standardList:edit")
	@GetMapping("/edit/{id}")
	public String edit(@PathVariable("id") String id, ModelMap mmap) {
		BusStandardListEntity busStandardListEntity = busStandardListService.getById(id);
		mmap.put("standardList", busStandardListEntity);
		return urlPrefix + "/edit";
	}

	/**
	 * 修改出入库保存
	 */
	@RepeatSubmit
	@RequiresPermissions("bus:standardList:edit")
	@BussinessLog(title = "修改", businessType = BusinessType.UPDATE)
	@RequestMapping(value = "/edit", method = RequestMethod.POST)
	@ResponseBody
	public ResponseData edit(BusStandardListEntity busStandardListEntity) {
		ValidatorUtil.validateEntity(busStandardListEntity);
		Date date = new Date();//创建一个时间对象，获取到当前的时间
		busStandardListEntity.setUpdateTime(date);
		String userName=UserUtils.getUserInfo().getName();
		busStandardListEntity.setCreateBy(userName);
		return busStandardListService.updateById(busStandardListEntity) ? success() : error("修改失败!");
	}

	/**
	 * 新增参数配置
	 */
	@RequiresPermissions("bus:standardList:add")
	@GetMapping("/add/{id}")
	public String add(@PathVariable("id") Long id, ModelMap mmap){
		//mmap.put("comp",  busClassifyService.findCompById(id));
System.out.println("1111111111");
		System.out.println(id);
		BusStandardEntity busStandardEntity = busStandardService.findCompById(id);
		System.out.println("222222");
		mmap.put("standard",  busStandardEntity);
		return urlPrefix + "/add";
	}


	/**
	 * 新增保存
	 */
	@RepeatSubmit
	@RequiresPermissions("bus:standardList:add")
	@BussinessLog(title = "认领", businessType = BusinessType.INSERT)
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	public ResponseData addSave(@Validated BusStandardListEntity busStandardListEntity) {
		//校验参数
		ValidatorUtil.validateEntity(busStandardListEntity);
		Date date = new Date();//创建一个时间对象，获取到当前的时间
		//SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//注意月份是MM
		busStandardListEntity.setCreateTime(date);
//		Long userId= UserUtils.getUserInfo().getId();
//		SysUserEntity sysUserEntity=busEquipmentService.getSysById(userId);
//		busEquipmentEntity.setCreateBy(sysUserEntity.getName());
		String userName=UserUtils.getUserInfo().getName();
		busStandardListEntity.setCreateBy(userName);
		return busStandardListService.save(busStandardListEntity) ? success() : error("新增失败!");
	}

	/**
	 * 修改出入库保存
	 */

	@RequiresPermissions("bus:standardList:checkout")
	@BussinessLog(title = "出库", businessType = BusinessType.INSERT)
	@RequestMapping(value = "/checkout", method = RequestMethod.POST)
	@ResponseBody
//	@GetMapping("/checkout/{id}")
	public ResponseData checkout(String id, ModelMap mmap) {
		System.out.println("1111111111111111111111");
		ValidatorUtil.validateEntity(id);
		Long ids=Long.parseLong(id);
		return busStandardListService.updateCheck(ids) ? success() : error("修改失败!");
	}



	@BussinessLog(title = "导出", businessType = BusinessType.EXPORT)
	@RequiresPermissions("bpm:standardList:export")
	@PostMapping("/export")
	@ResponseBody
	public ResponseData export(@RequestParam Map<String, Object> params) throws Exception {
		WriteCellStyle headWriteCellStyle = new WriteCellStyle();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH时mm分");
		String date = sdf.format(new Date());
		String fileName =  "设备信息";
//		// 表头
//		List<List<String>> heads = new ArrayList<List<String>>();
//		StringBuffer sb = new StringBuffer("三联单库查询：");
//		sb.append("表单名："+fileName + "操作时间:"+ date);
//
		fileName = ToolUtil.encodingExcelFilename(fileName);
		String folder = Global.getTempPath() + File.separator + "pio" + File.separator;
//		FileUtil.touch(folder + fileName);
		List<BusStandardListEntity> listData = busStandardListService.findList(params);
//		List pilebodysList = pilebodycheckService.pilebodystatisticsmonth(sysDepartDto, month);
//设置序号
//		for (int i = 1; i <= listData.size(); i++) {
//			listData.get(i - 1).setOrderNum(i + "");
//		}
//		response.setContentType("application / vnd.ms - excel");
//		response.setCharacterEncoding("utf - 8");
//// 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
//		String fileName = URLEncoder.encode("存量建筑垃圾堆体治理进度月报表", "UTF - 8");
//		response.setHeader("Content - disposition", "attachment; filename ="+fileName + ".xls");
//内容样式策略
		WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
//垂直居中,水平居中
		contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
		contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
		contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
		contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
		contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
		contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);
//设置 自动换行
		contentWriteCellStyle.setWrapped(true);
// 字体策略
		WriteFont contentWriteFont = new WriteFont();
// 字体大小
		contentWriteFont.setFontHeightInPoints((short) 12);
		contentWriteCellStyle.setWriteFont(contentWriteFont);
//头策略使用默认



		//excel如需下载到本地,只需要将response.getOutputStream()换成File即可(注释掉以上response代码)
		EasyExcel.write(folder + fileName, BusEquipmentEntity.class)
				//设置输出excel版本,不设置默认为xlsx
				//.excelType(ExcelTypeEnum.XLS).head(ProjectSanLianEntity.class)
				//设置拦截器或自定义样式
				.registerWriteHandler(new MonthSheetWriteHandler())
				.registerWriteHandler(new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle))
				.sheet("设备信息")
				//设置默认样式及写入头信息开始的行数
				.useDefaultStyle(true).relativeHeadRowIndex(3)
				//这里的addsumColomn方法是个添加合计的方法,可删除
				.doWrite(listData);

		return success(fileName);
	}



}
